<template>
  <div id="upload" style="width: 400px; ">
    <el-row>
      <el-upload
        class="upload-demo"
				:headers="headers"
				multiple
				:limit='1'
        action="/api/upload/account"
        :file-list="fileList"
        :auto-upload="false"
				:on-success="onSuccess"
				:on-error="onError"
				:on-change="onChange"
				:before-upload="beforeUpload"
      >
        <el-button slot="trigger" size="small" type="primary"
          >选取文件</el-button
        >
        <el-button
          style="margin-left: 10px;"
          size="small"
          type="success"
          @click="submitUpload"
          >上传到服务器</el-button
        >
				<div slot="tip" class="el-upload__tip">每次只能上传一个文件</div>
      </el-upload>
    </el-row>
  </div>
</template>

<script>
import { uploadAccount } from "@/network/index.js";
export default {
  name: "Upload",
  data() {
    return {
      fileList: [],
      headers: {
        Authorization: "bearer " + this.$store.getters.getToken,
        "Content-Type": "multipart/form-data",
      },
    };
  },
  methods: {
    open(message, type) {
      this.$message({
        message,
        type,
      });
    },
    beforeUpload(file) {
      console.log(file);
    },
    onChange(file, fileList) {
      this.fileList = fileList;
    },
    submitUpload() {
      let token = this.$store.getters.getToken;
      let formData = new FormData();
      formData.append("file", this.fileList[0].raw);
      uploadAccount(token, formData)
        .then((res) => {
					console.log(res);
					this.open('添加成功','success');
					this.fileList = []
        })
        .catch((err) => {
					this.open('添加失败','warning');
					console.log(err);
        });
    },

    onSuccess() {
      this.open("上传成功", "success");
    },
    onError(err, file, fileList) {
      this.open("上传失败", "warning");
      console.log(err, file, fileList);
    },
  },
  components: {},
};
</script>

<style></style>
